//
//  WeChatLoginViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/10/8.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "WeChatLoginViewController.h"
#import "RegisterViewController.h"
#import "ForgetPassWordViewController.h"

@interface WeChatLoginViewController ()<UITextFieldDelegate>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UITextField * phoneNumTextField;//电话号
@property (nonatomic, strong)UITextField * codeTextField;//密码
@property (nonatomic, strong)UIButton * forgetPassWordBtn;//忘记密码
@property (nonatomic, strong)UIButton * loginBtn;//绑定按钮
@property (nonatomic, strong)NSTimer * timer;
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * verificationString;
@property (nonatomic, strong)UIButton * registerBtn;//注册密码
@end

@implementation WeChatLoginViewController(networking)
//登录接口
- (void)loginData{
    NSDictionary * dic = @{
                           @"phone":self.phoneNumTextField.text,
                           @"password":self.codeTextField.text,
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"usiosApi/login" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [UserModel sharedInstanced].token = [responseObject[@"list"] objectForKey:@"token"];
            [UserModel sharedInstanced].mobile = [responseObject[@"list"] objectForKey:@"phone"];
            int64_t delayInSeconds = 1;// 延迟的时间
            /*
             *@parameter 1,时间参照，从此刻开始计时
             *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
             */
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self hiddenProgressHUD];
                [self dismissViewControllerAnimated:YES completion:nil];
//                self.beThereThePageBlock();
            });
        }else{
            [self hiddenProgressHUD];
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end
@implementation WeChatLoginViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"登录";
    //回退键
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn addTarget:self action:@selector(backBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    [self.view addSubview:self.tableView];
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.tableHeaderView = self.headerView;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT)];
        //标题
        UIImageView * titleLab = [[UIImageView alloc] initWithFrame:CGRectMake(0, 30/WIDTH_6_SCALE, 60/WIDTH_6_SCALE, 60/WIDTH_6_SCALE)];
        titleLab.image = [UIImage imageNamed:@"appSelf"];
        titleLab.layer.cornerRadius = 30/WIDTH_6_SCALE;
        titleLab.layer.masksToBounds = YES;
        titleLab.centerX = SCREEN_WIDTH/2;
        [_headerView addSubview:titleLab];
        //手机号
        self.phoneNumTextField = [[UITextField alloc] initWithFrame:CGRectMake(40/WIDTH_6_SCALE, 43/WIDTH_6_SCALE + titleLab.bottom, SCREEN_WIDTH - 80/WIDTH_6_SCALE, 40/WIDTH_6_SCALE)];
        self.phoneNumTextField.delegate = self;
        self.phoneNumTextField.placeholder = @"请输入手机号";
        self.phoneNumTextField.font = DEF_FontSize_14;
        self.phoneNumTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * phoneNumPlaceHoldImgBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39/WIDTH_6_SCALE, self.phoneNumTextField.height)];
        phoneNumPlaceHoldImgBG.backgroundColor = [UIColor clearColor];
        UIImageView *phoneNumImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 13/WIDTH_6_SCALE, 11/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        phoneNumImageView.image = [UIImage imageNamed:@"boundPhone"];
        [phoneNumPlaceHoldImgBG addSubview:phoneNumImageView];
        self.phoneNumTextField.leftView = phoneNumPlaceHoldImgBG;
        self.phoneNumTextField.backgroundColor = getColor(mainColor);
        [_headerView addSubview:self.phoneNumTextField];
        //验证码
        self.codeTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.phoneNumTextField.bottom + 16/WIDTH_6_SCALE, self.phoneNumTextField.width, self.phoneNumTextField.height)];
        self.codeTextField.delegate = self;
        self.codeTextField.placeholder = @"请输入密码";
        self.codeTextField.secureTextEntry = YES;
        self.codeTextField.font = DEF_FontSize_14;
        self.codeTextField.backgroundColor = getColor(mainColor);
        self.codeTextField.leftViewMode = UITextFieldViewModeAlways;
        UIView * verificationCodePlaceHoldImgBG = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 39/WIDTH_6_SCALE, self.codeTextField.height)];
        verificationCodePlaceHoldImgBG.backgroundColor = [UIColor clearColor];
        UIImageView *verificationCodeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(15/WIDTH_6_SCALE, 13/WIDTH_6_SCALE, 14/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        verificationCodeImageView.image = [UIImage imageNamed:@"lock"];
        [verificationCodePlaceHoldImgBG addSubview:verificationCodeImageView];
        self.codeTextField.leftView = verificationCodePlaceHoldImgBG;
        self.codeTextField.backgroundColor = getColor(mainColor);
        [_headerView addSubview:self.codeTextField];
        //忘记密码
        self.forgetPassWordBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.codeTextField.bottom + 10/WIDTH_6_SCALE, 80/WIDTH_6_SCALE, 20/WIDTH_6_SCALE)];
        [self button:self.forgetPassWordBtn withBGColor:[UIColor clearColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:YES withViwe:_headerView];
        [self.forgetPassWordBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
        [self.forgetPassWordBtn setTitleColor:getColor(mainRedColor) forState:UIControlStateNormal];
        self.forgetPassWordBtn.titleLabel.font = DEF_FontSize_12;
        [self.forgetPassWordBtn addTarget:self action:@selector(forgetPassWordBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        //注册
        self.registerBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.phoneNumTextField.right - self.forgetPassWordBtn.width, self.forgetPassWordBtn.top, self.forgetPassWordBtn.width, self.forgetPassWordBtn.height)];
        [self button:self.registerBtn withBGColor:[UIColor clearColor] withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:YES withViwe:_headerView];
        [self.registerBtn setTitle:@"注册" forState:UIControlStateNormal];
        [self.registerBtn setTitleColor:getColor(mainRedColor) forState:UIControlStateNormal];
        self.registerBtn.titleLabel.font = DEF_FontSize_12;
        [self.registerBtn addTarget:self action:@selector(registerBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        //绑定按钮
        self.loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.phoneNumTextField.left, self.codeTextField.bottom + 63/WIDTH_6_SCALE, self.phoneNumTextField.width, 40/WIDTH_6_SCALE)];
        [self.loginBtn setBackgroundColor:getColor(mainColor)];
        [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        self.loginBtn.titleLabel.font = DEF_FontSize_14;
        [self.loginBtn setTitleColor:getColor(@"898989") forState:UIControlStateNormal];
        [self.loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_headerView addSubview:self.loginBtn];
        _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.loginBtn.bottom + 20/WIDTH_6_SCALE);
    }return _headerView;
}
#pragma mark - action
- (void)forgetPassWordBtnClick:(UIButton *)sender{
    NSLog(@"忘记密码");
    ForgetPassWordViewController * vc = [[ForgetPassWordViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)registerBtnClick:(UIButton *)sender{
    NSLog(@"注册");
    RegisterViewController * vc = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)backBtnClick{
//    [self dismissViewControllerAnimated:YES completion:nil];
    if (self.backHomePageBlock) {
        self.backHomePageBlock();
    }
}
- (void)loginBtnClick:(UIButton *)sender{
    NSLog(@"登录");
    if (self.phoneNumTextField.text.length == 0 || [self.phoneNumTextField.text isEqualToString:@""] || self.phoneNumTextField.text == nil) {
        [self.view makeToast:@"请输入手机号" duration:1 position:CSToastPositionCenter];
        return;
    }
    if ([self valiMobile:self.phoneNumTextField.text]) {
        if (self.codeTextField.text.length == 0 || [self.codeTextField.text isEqualToString:@""] || self.codeTextField.text == nil) {
            [self.view makeToast:@"请输入密码" duration:1 position:CSToastPositionCenter];
        }else{
            [self loginData];
        }
    }else{
        [self.view makeToast:@"请输入正确的手机号" duration:1 position:CSToastPositionCenter];
    }
}
#pragma mark - textFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.phoneNumTextField) {
        self.phoneString = string;
    }
    if (textField == self.codeTextField) {
        self.verificationString = string;
    }
    if (self.phoneString.length && self.verificationString.length > 0) {
        [self.loginBtn setBackgroundColor:getColor(mainRedColor)];
        [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        self.loginBtn.userInteractionEnabled = YES;
    }else{
        [self.loginBtn setBackgroundColor:getColor(mainColor)];
        [self.loginBtn setTitleColor:getColor(@"898989") forState:UIControlStateNormal];
        self.loginBtn.userInteractionEnabled = NO;
    }
    return YES;
}
@end
